package com.doge.walknovel.push

import android.content.Intent
import com.doge.walknovel.utils.appContext
import com.doge.walknovel.utils.log
import com.doge.walknovel.utils.toJson
import com.google.firebase.messaging.RemoteMessage

class FCMService : com.google.firebase.messaging.FirebaseMessagingService() {
    companion object {
        const val NOTIFICATION_BODY = "body"
        const val NOTIFICATION_TITLE = "title"
        const val NOTIFICATION_IMAGE_URL = "imageUrl"
        const val NOTIFICATION_EXTRA = "extra"
        val FIREBASE_MESSAGE by lazy { "${appContext.packageName}.push.FIREBASE_MESSAGE" }
    }

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        // received message when app living
        log("Push onMessageReceived title ${remoteMessage.notification?.title} body ${remoteMessage.notification?.body} image ${remoteMessage.notification?.imageUrl} data ${remoteMessage.data}")
        val pushIntent = processRemoteMessage(remoteMessage) ?: return
        sendBroadcast(pushIntent.apply {
            action = FIREBASE_MESSAGE
        })
    }

    private fun processRemoteMessage(remoteMessage: RemoteMessage?): Intent? {
        val message = remoteMessage ?: return null
        return Intent().apply {
            if (message.data.isNotEmpty()) {
                putExtra(NOTIFICATION_EXTRA, remoteMessage)
            }
            putExtra(NOTIFICATION_TITLE, message.notification?.title ?: "")
            putExtra(NOTIFICATION_BODY, message.notification?.body ?: "")
            putExtra(NOTIFICATION_IMAGE_URL, message.notification?.imageUrl?.toString() ?: "")
        }
    }

    override fun onNewToken(token: String) {
        log("PushHelper FCMService onNewToken token $token")
        PushHelper.handleToken(token) // sendRegistrationToServer
    }
}


